package com.kecheng.xinmei.controller.upload;

import com.kecheng.xinmei.entity.Picture;
import com.kecheng.xinmei.entity.User;
import com.kecheng.xinmei.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
 * @author gaokecheng
 * @version 1.0
 * @date 2020/11/20 4:21 下午
 */
@RestController
@RequestMapping(value = "/upload")
public class UploadController {

    @RequestMapping(value = "/picture",method = RequestMethod.POST)
    public Picture uploadPicture(@RequestParam("file") MultipartFile file) {
        Picture picture = new Picture();
        List<String> list = new ArrayList<>();
        picture.setErrno("0");
        try {
            if (file.isEmpty()) {
                return picture;
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            System.out.println("上传的文件名为：" + fileName);
           String mainName = UUID.randomUUID().toString();
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            System.out.println("文件的后缀名为：" + suffixName);

            // 设置文件存储路径
            String filePath = "/Users/vic/Downloads/picture/";
            System.out.println(filePath);
            String path = filePath + mainName + suffixName;

            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入
            list.add("http://121.196.151.13:8099/"+mainName+suffixName);
            picture.setData(list);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return picture;

    }
}
